<template>
  <div class="account-container">
    <h2  >账号管理</h2>
    <!-- 查询 -->
    <div class="search-container">
      <el-button
          @click="openAssignDialog"
          type="success"
          plain
          class="search-button"
      >
        分配账号
      </el-button>
    </div>

    <!-- 错误信息 -->
    <div class="error-message">{{ errorMessage }}</div>

    <!-- 账号信息表格 -->
    <el-table
        :data="allAccounts"
        class="account-table"
        header-cell-class-name="table-header"
    >
      <el-table-column
          label="序号"
          type="index"
          width="80px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="employee_name"
          label="员工姓名"
          width="150px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="username"
          label="用户名"
          width="180px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="email"
          label="手机号"
          width="200px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="password"
          label="密码"
          width="180px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="role_name"
          label="角色"
          width="150px"
          align="center"
      ></el-table-column>
      <el-table-column label="操作" width="197px" align="center">
        <template #default="scope">
          <el-button @click="openChangePasswordDialog(scope.row)" type="text" size="small">更改密码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分配账号对话框 -->
    <el-dialog
        v-model="assignDialog"
        title="分配账号"
        class="assign-dialog"
    >
      <el-form :model="account" class="assign-form">
        <el-form-item label="员工姓名" class="form-item">
          <el-select
              v-model="selectedEmployeeId"
              placeholder="请选择员工"
              style="width: 100%"
          >
            <el-option
                v-for="employee in unassignedEmployees"
                :key="employee.id"
                :label="employee.employeeName"
                :value="employee.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户名" class="form-item">
          <el-input v-model="account.username" class="form-input" placeholder="请输入用户名（6-20个字符）"></el-input>
          <div v-if="!isValidUsername" class="error-text">用户名必须为6-20个字符</div>
        </el-form-item>
        <el-form-item label="密码" class="form-item">
          <el-input
              v-model="account.password"
              type="password"
              class="form-input"
              placeholder="请输入密码（8-20个字符）"
          ></el-input>
          <div v-if="!isValidPassword" class="error-text">密码必须为8-20个字符</div>
        </el-form-item>
        <el-form-item label="手机号" class="form-item">
          <el-input v-model="account.email" class="form-input" placeholder="请输入手机号"></el-input>
          <div v-if="!isValidEmail" class="error-text">请输入有效的手机号</div>
        </el-form-item>
        <el-form-item label="角色" class="form-item">
          <el-select
              v-model="account.role_id"
              placeholder="请选择角色"
              style="width: 100%"
          >
            <el-option
                v-for="role in roleOptions"
                :key="role.value"
                :label="role.label"
                :value="role.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="saveAccount" class="dialog-button">保存</el-button>
        <el-button @click="closeAssignDialog" class="dialog-button">取消</el-button>
      </div>
    </el-dialog>

    <!-- 更改密码对话框 -->
    <el-dialog
        v-model="changePasswordDialog"
        title="更改密码"
        class="assign-dialog"
    >
      <el-form :model="passwordForm" class="assign-form">
        <el-form-item label="新密码" class="form-item">
          <el-input
              v-model="passwordForm.newPassword"
              type="password"
              class="form-input"
              placeholder="请输入新密码（8-20个字符）"
          ></el-input>
          <div v-if="!isValidNewPassword" class="error-text">新密码必须为8-20个字符</div>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="saveNewPassword" class="dialog-button">保存</el-button>
        <el-button @click="closeChangePasswordDialog" class="dialog-button">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue';
import http from '@/axios/http';
import { ElMessage } from 'element-plus';

// 存放所有账号信息
let allAccounts = ref([]);

// 存放未分配账号的员工数据集合
let unassignedEmployees = ref([]);

// 报错提示
let errorMessage = ref("");

// 对话框显示控制
let assignDialog = ref(false);
let changePasswordDialog = ref(false);

// 分配账号的绑定数据
let account = ref({
  username: '',
  password: '',
  email: '',
  role_id: 2, // 默认值为2（员工）
});

// 当前选中的员工ID
let selectedEmployeeId = ref(null);

// 角色选项
let roleOptions = ref([
  { label: '员工', value: 2 },
  // { label: '管理员', value: 1 },
]);

// 更改密码表单数据
let passwordForm = ref({
  userId: null,
  newPassword: ''
});

// 验证用户名是否有效
const isValidUsername = computed(() => {
  return account.value.username.length >= 6 && account.value.username.length <= 20;
});

// 验证密码是否有效
const isValidPassword = computed(() => {
  return account.value.password.length >= 8 && account.value.password.length <= 20;
});

// 验证新密码是否有效
const isValidNewPassword = computed(() => {
  return passwordForm.value.newPassword.length >= 8 && passwordForm.value.newPassword.length <= 20;
});

// 验证邮箱是否有效
const isValidEmail = computed(() => {
  const emailRegex = /^1[3-9]\d{9}$/;
  return emailRegex.test(account.value.email);
});

// 获取所有账号信息
function fetchAllAccounts() {
  http.get('/glsb/all-accounts').then((response) => {
    let result = response.data;
    if (result.result === 'success') {
      allAccounts.value = result.data;
    } else {
      errorMessage.value = result.error;
      ElMessage.error(result.error);
    }
  });
}

// 获取未分配账号的员工列表
function fetchUnassignedEmployees() {
  http.get('/glsb/unassigned-employees').then((response) => {
    let result = response.data;
    if (result.result === 'success') {
      unassignedEmployees.value = result.data;
    } else {
      errorMessage.value = result.error;
      ElMessage.error(result.error);
    }
  });
}

// 显示分配账号对话框
function openAssignDialog() {
  fetchUnassignedEmployees();
  assignDialog.value = true;
}

// 关闭分配账号对话框
function closeAssignDialog() {
  assignDialog.value = false;
  account.value = {
    username: '',
    password: '',
    email: '',
    role_id: 2, // 默认值为2（员工）
  };
  selectedEmployeeId.value = null;
}

// 分配账号
function saveAccount() {
  if (!selectedEmployeeId.value || !account.value.username || !account.value.password || !account.value.email || !account.value.role_id) {
    ElMessage.error("请填写所有必填项");
    return;
  }
  if (!isValidUsername.value) {
    ElMessage.error("用户名必须为6-20个字符");
    return;
  }
  if (!isValidPassword.value) {
    ElMessage.error("密码必须为8-20个字符");
    return;
  }
  if (!isValidEmail.value) {
    ElMessage.error("请输入有效的手机号");
    return;
  }
  http.post('/glsb/assign-account', {
    employeeId: selectedEmployeeId.value,
    username: account.value.username,
    password: account.value.password,
    email: account.value.email,
    role_id: account.value.role_id,
  }).then((response) => {
    let result = response.data;
    if (result.result === 'success') {
      closeAssignDialog();
      fetchAllAccounts();
      ElMessage.success('账号分配成功');
    } else {
      // 新增错误类型判断
      if (result.error.includes('username')) {
        ElMessage.error('用户名已存在，请更换');
      } else if (result.error.includes('email')) {
        ElMessage.error('手机号已被注册');
      } else {
        ElMessage.error(result.error);
      }
    }
  }).catch((error) => {
    // 新增网络错误处理
    ElMessage.error('请求失败: ' + error.message);
  });
}

// 打开更改密码对话框
function openChangePasswordDialog(row) {
  passwordForm.value.userId = row.id;
  changePasswordDialog.value = true;
}

// 关闭更改密码对话框
function closeChangePasswordDialog() {
  changePasswordDialog.value = false;
  passwordForm.value = {
    userId: null,
    newPassword: ''
  };
}

// 保存新密码
function saveNewPassword() {
  if (!passwordForm.value.newPassword) {
    ElMessage.error("请输入新密码");
    return;
  }
  if (!isValidNewPassword.value) {
    ElMessage.error("新密码必须为8-20个字符");
    return;
  }
  http.post('/glsb/change-password', {
    userId: passwordForm.value.userId,
    newPassword: passwordForm.value.newPassword
  }).then((response) => {
    let result = response.data;
    if (result.result === 'success') {
      closeChangePasswordDialog();
      fetchAllAccounts();
      ElMessage.success('密码更改成功');
    } else {
      ElMessage.error(result.error);
    }
  });
}

// 页面初始化
onMounted(() => {
  fetchAllAccounts();
});
</script>

<style scoped>
.account-container {
  padding: 20px;
}
.error-text {
  color: red;
  font-size: 12px;
  margin-top: 4px;
}
</style>